Promise/A+规范

  1. 三种状态 pending || fullfiled(resolved) || rejected
  2. 当处于pending状态的时候,可以转移到fullfiled(resolved)或者rejected状态
  3. 当处于fullfiled(resolved)状态或者rejected状态的时候,就不可变
  • 必须有一个then异步执行方法,then接收2个参数并且必须返回一个promise:
  1. onFullfiled 用来接收promise成功的值
  2. onRejected 用语接收promise失败的原因
  3. promise.prototype.then = function(onFullfiled,onRejected){}

面试够用版

        function myPromise(constructor){
            let self = this;
            self.status = 'pendding';
            self.value = undefined;
            self.reason = undefined;

            function resolve(value){
                if(self.status === 'pendding'){
                    self.value = value;
                    self.status = 'resolved'
                }
            }

            function reject(reason){
                if(self.status === 'pendding'){
                    self.reason = reason;
                    self.status = 'rejected'
                }
            }

            try{
                constructor(resolve,reject)
            }catch(e){
                reject(e)
            }
        }

        myPromise.prototype.then = function(onResolved,onRejected){
            let self = this;
            // switch(self.status){
            //     case 'resolved':
            //         onFullfiled(self.value)
            //         break;
            //     case 'rejected':
            //         onRejected(self.reason)
            //         break;
            //     default:
            // }
            if(self.status === 'resolved'){
                onResolved(self.value)
            }else if(self.status === 'rejected'){
                onRejected(self.reason)
            }else{
                return false
            }
        }

        var p = new myPromise((resolve,reject) => {
            resolve(1)
        })
        p.then((x) => {
            console.log(x)
        })

渣渣辉
1.3k 声望147 粉丝